package Action;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import Dao.UserDao;
import Form.User;

public class RegistAction extends SimpleFormController {

	private String fail_view;
	private String success_view;
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setFail_view(String fail_view) {
		this.fail_view = fail_view;
	}

	public void setSuccess_view(String success_view) {
		this.success_view = success_view;
	}

	// @Override
	// @RequestMapping(value="login", method=RequestMethod.POST)
	protected ModelAndView onSubmit(Object command, BindException errors)
			throws Exception {
		User user = (User) command;
		if (regist(user) == 1) {
			return new ModelAndView(success_view);
		} else {
			return new ModelAndView(fail_view);
		}
	}

	private int regist(User user) throws Exception {
		int result;
		if(userDao.getUserByUsername(user.getUsername())!=null){
			return 0;
		}
		try {
			result = userDao.insertUser(user);
		} catch (Exception e) {
			throw e;
		}

		return result;
	}

}
